package org.blog.conifg;

import org.blog.inteceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

/**
 *  MVC 配置类
 */
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Resource
    private TokenInterceptor tokenInterceptor;

    /**
     * CORS 解决跨域请求
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowedOriginPatterns("*")
                .allowCredentials(true);
    }

    /**
     * 异步请求配置
     * @param configurer
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setTaskExecutor(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(3)));
        configurer.setDefaultTimeout(30000); //设置超时时间为30s
    }

    /**
     * 配置拦截器、拦截路径
     * 每次请求到拦截的路径，就会去执行拦截器中的方法
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePath = new ArrayList<>();
        //排除拦截，除了注册登录(此时还没token)和swagger API文档，其他都拦截
        excludePath.add("/article/**");
        excludePath.add("/avatar/**");
        excludePath.add("/image/**");
        excludePath.add("/users/login");            //登录
        excludePath.add("/users/register");         //注册
        excludePath.add("/users/session/**");       //获取openid
        excludePath.add("/doc.html");               //swagger
        excludePath.add("/swagger-ui/*");           //swagger
        excludePath.add("/swagger-resources/**");   //swagger
        excludePath.add("/v2/api-docs");            //swagger
        excludePath.add("/webjars/**");             //swagger
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")             //对所有请求进行拦截
                .excludePathPatterns(excludePath);  //排除路径
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /**
     * 静态资源访问
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler("/**")
//                .addResourceLocations("file:F:/微信小程序开发/Postgraduate/uploadFile/");
    }
}
